#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
打包脚本：将Python程序打包为Windows可执行文件(.exe)
"""

import os
import sys
import shutil
import subprocess
from pathlib import Path

# 配置参数
APP_NAME = "瀚越包装方案匹配工具"
MAIN_SCRIPT = "temp_app.py"  # 如果src/main.py存在，使用src/main.py
ICON_FILE = None  # 可以设置为.ico文件路径

# 检查是否存在src/main.py
if os.path.exists("src/main.py"):
    MAIN_SCRIPT = "src/main.py"


def check_pyinstaller():
    """检查PyInstaller是否已安装"""
    try:
        subprocess.run(
            ["pyinstaller", "--version"],
            check=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
        )
        return True
    except (subprocess.CalledProcessError, FileNotFoundError):
        return False


def install_pyinstaller():
    """安装PyInstaller"""
    print("正在安装PyInstaller...")
    try:
        subprocess.run(
            [
                sys.executable,
                "-m",
                "pip",
                "install",
                "pyinstaller",
                "-i",
                "https://pypi.tuna.tsinghua.edu.cn/simple",
            ],
            check=True,
        )
        print("PyInstaller安装成功")
        return True
    except subprocess.CalledProcessError as e:
        print(f"PyInstaller安装失败: {e}")
        return False


def clean_build_files():
    """清理之前的构建文件"""
    print("清理之前的构建文件...")
    for dir_name in ["build", "dist"]:
        if os.path.exists(dir_name):
            shutil.rmtree(dir_name)
            print(f"已删除目录: {dir_name}")

    spec_file = f"{MAIN_SCRIPT.rsplit('.', 1)[0]}.spec"
    if os.path.exists(spec_file):
        os.remove(spec_file)
        print(f"已删除文件: {spec_file}")


def build_executable():
    """使用PyInstaller构建可执行文件"""
    print(f"开始构建{APP_NAME}可执行文件...")

    # 构建PyInstaller命令
    cmd = [
        "pyinstaller",
        "--onefile",  # 打包为单个可执行文件
        "--windowed",  # 无控制台窗口
        "--name",
        APP_NAME,
        "--add-data",
        f"{MAIN_SCRIPT};.",  # 添加主脚本
    ]

    # 添加其他需要打包的文件
    if os.path.exists("check_excel_env.py"):
        cmd.extend(["--add-data", "check_excel_env.py;."])

    if os.path.exists("giant-logo.png"):
        cmd.extend(["--add-data", "giant-logo.png;."])

    # 添加src目录下的所有模块文件
    if os.path.exists("src"):
        for root, dirs, files in os.walk("src"):
            for file in files:
                if file.endswith(".py"):
                    file_path = os.path.join(root, file)
                    rel_path = os.path.relpath(file_path, start="src")
                    dest_path = os.path.dirname(rel_path)
                    if dest_path == ".":
                        dest_path = "src"
                    else:
                        dest_path = os.path.join("src", dest_path)
                    cmd.extend(["--add-data", f"{file_path};{dest_path}"])

    # 如果有图标文件，添加图标参数
    if ICON_FILE and os.path.exists(ICON_FILE):
        cmd.extend(["--icon", ICON_FILE])

    # 添加主脚本到命令
    cmd.append(MAIN_SCRIPT)

    try:
        # 执行PyInstaller命令
        print(f"执行命令: {' '.join(cmd)}")
        subprocess.run(cmd, check=True)
        print(f"{APP_NAME}可执行文件构建成功!")
        print(f"可执行文件位置: {os.path.join('dist', f'{APP_NAME}.exe')}")
        return True
    except subprocess.CalledProcessError as e:
        print(f"构建失败: {e}")
        return False


def create_bat_runner():
    """创建一个批处理文件，用于运行可执行文件"""
    bat_content = f"""
@echo off
REM {APP_NAME}运行脚本
cd /d %~dp0
echo 正在启动{APP_NAME}...
if exist dist\{APP_NAME}.exe (
    echo 运行可执行文件...
    dist\{APP_NAME}.exe
) else (
    echo 错误: 未找到可执行文件，请先运行build_exe.py进行打包
)

pause
"""

    with open("run_exe.bat", "w", encoding="utf-8") as f:
        f.write(bat_content)

    print("已创建运行脚本: run_exe.bat")


def main():
    """主函数"""
    print(f"=== {APP_NAME} 打包工具 ===")

    # 检查并安装PyInstaller
    if not check_pyinstaller():
        if not install_pyinstaller():
            print("无法继续打包，请手动安装PyInstaller后重试")
            return False

    # 清理之前的构建文件
    clean_build_files()

    # 构建可执行文件
    if build_executable():
        # 创建运行脚本
        create_bat_runner()
        print("\n打包任务完成!")
        print(f"请运行生成的可执行文件: dist\{APP_NAME}.exe")
        print("或者使用运行脚本: run_exe.bat")
        return True
    else:
        print("打包失败，请检查错误信息并修复问题")
        return False


if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)
